package com.dl.base.api.request

import androidx.lifecycle.MutableLiveData
import com.dl.base.api.response.ListData
import java.lang.RuntimeException

class ReqPage(val pageSize: Int = PAGE_SIZE) {
    companion object {
        const val PAGE_SIZE = 10
    }

    private var startPageNum = 1
    private var pageNumber = startPageNum
    private var lastPageInt = startPageNum
    private var sourceData: MutableLiveData<out ListData<*>?>? = null

    /**
     * 需要绑定请求结果的liveData才可以监听pageIndex的变化
     */
    constructor(
        data: MutableLiveData<out ListData<*>?>,
        pageSize: Int = PAGE_SIZE
    ) : this(pageSize) {
        sourceData = data
    }

    fun bind(data: MutableLiveData<out ListData<*>?>) {
        sourceData = data
    }

    /**
     * 页数
     */
    fun pageIndex(isRefresh: Boolean = false): Int {
        if (sourceData == null)
            throw RuntimeException("需要绑定请求结果的liveData才可以监听pageIndex的变化")

        return if (isRefresh) {
            pageNumber = startPageNum
            1
        } else {
            if (sourceData!!.value == null) {
                lastPageInt
            } else {
                lastPageInt = sourceData!!.value!!.index + 1
                lastPageInt
            }
        }
    }

    /**
     * 序号的起始值
     */
    fun setStartPageNumber(num: Int) {
        startPageNum = num
        pageNumber = startPageNum
    }

    /**
     * 每条的序号
     */
    fun pageNumber(): Int {
        return pageNumber++
    }
}